package org.luxor.commons.workflow.listener;

import org.activiti.bpmn.model.MultiInstanceLoopCharacteristics;
import org.activiti.engine.delegate.event.ActivitiActivityEvent;
import org.activiti.engine.delegate.event.ActivitiEvent;
import org.activiti.engine.impl.bpmn.behavior.ParallelMultiInstanceBehavior;
import org.activiti.engine.impl.bpmn.behavior.SequentialMultiInstanceBehavior;
import org.luxor.commons.workflow.component.cache.DeploymentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

/**
 * 活动节点开始执行(在开始前调用)
 *
 * @author Mr.yan  @date 2021/10/27
 */
public class ActivityStartedListener implements ActivitiEventHandler {

    private static final Logger log = LoggerFactory.getLogger(ActivityStartedListener.class);

    @Override
    public void handle(ActivitiEvent event) {
        if (event != null && StringUtils.hasText(event.getProcessInstanceId())) {
            DeploymentContext.setProcInstId(event.getProcessInstanceId());
        }
        ActivitiActivityEvent activityEvent = (ActivitiActivityEvent) event;
        log.debug("活动节点开始(ActivityStartedListener). ActivityId: " + activityEvent.getActivityId()
                + "(" + activityEvent.getActivityName() + "),ProcInstId: " + activityEvent.getProcessInstanceId()
                + ",ExecutionId: " + activityEvent.getExecutionId()
                + ",BehaviorClass: " + activityEvent.getBehaviorClass());
    }

    /**
     * 是多实例节点?
     *
     * @param behaviorClass
     * @return boolean
     */
    private boolean isMultiInstance(String behaviorClass) {
        if (behaviorClass.equals(SequentialMultiInstanceBehavior.class.getName())) {
            return true;
        }
        if (behaviorClass.equals(ParallelMultiInstanceBehavior.class.getName())) {
            return true;
        }
        if (behaviorClass.equals(MultiInstanceLoopCharacteristics.class.getName())) {
            return true;
        }

        return false;
    }
}
